const express = require('express');
const router = express.Router();
const { SharedImage, User, AIRole, UserLike } = require('../models');
const { authenticateToken } = require('../middleware/auth');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { Op, sequelize } = require('sequelize');
const { sequelize: dbSequelize } = require('../config/db');

// 图片上传配置
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = 'public/uploads/shared-images/';
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, 'shared-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({
  storage,
  fileFilter: (req, file, cb) => {
    // 只允许图片文件
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('只允许上传图片文件'), false);
    }
  },
  limits: {
    fileSize: 10 * 1024 * 1024 // 10MB
  }
});

// 1. 分享图片到社区
router.post('/', authenticateToken, upload.single('image'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: '请上传图片文件' });
    }

    const { title, description, category, original_prompt, ai_role_id, tags, is_public } = req.body;

    if (!title || !category) {
      return res.status(400).json({ error: '标题和类别为必填项' });
    }

    // 解析标签
    let parsedTags = null;
    if (tags) {
      try {
        parsedTags = typeof tags === 'string' ? JSON.parse(tags) : tags;
      } catch (error) {
        return res.status(400).json({ error: '标签格式错误' });
      }
    }

    // 获取图片尺寸（简单实现）
    const imagePath = req.file.path;
    const stats = fs.statSync(imagePath);

    const sharedImage = await SharedImage.create({
      user_id: req.user.id,
      title,
      description,
      category,
      image_path: `/uploads/shared-images/${req.file.filename}`,
      original_prompt,
      ai_role_id: ai_role_id || null,
      tags: parsedTags,
      is_public: is_public !== 'false',
      file_size: stats.size,
      view_count: 0,
      like_count: 0
    });

    res.status(201).json({
      success: true,
      message: '图片分享成功',
      data: sharedImage
    });
  } catch (error) {
    console.error('分享图片失败:', error);
    res.status(500).json({ error: '分享图片失败' });
  }
});

// 2. 获取社区图片列表（支持分页和筛选）
router.get('/', async (req, res) => {
  try {
    console.log('获取社区图片列表请求参数:', req.query);
    const {
      page = 1,
      limit = 20,
      category,
      user_id,
      search,
      sort = 'latest',
      order = 'DESC'
    } = req.query;

    const offset = (page - 1) * limit;
    const where = { is_public: true };

    // 映射前端排序参数到数据库字段
    let sortField = 'created_at';
    let sortOrder = 'DESC';

    switch (sort) {
      case 'latest':
        sortField = 'created_at';
        sortOrder = 'DESC';
        break;
      case 'popular':
        sortField = 'view_count';
        sortOrder = 'DESC';
        break;
      case 'most_liked':
        sortField = 'like_count';
        sortOrder = 'DESC';
        break;
      default:
        sortField = 'created_at';
        sortOrder = 'DESC';
    }

    // 筛选条件
    if (category) {
      where.category = category;
    }
    if (user_id) {
      where.user_id = user_id;
    }
    if (search) {
      where[Op.or] = [
        { title: { [Op.like]: `%${search}%` } },
        { description: { [Op.like]: `%${search}%` } }
      ];
    }

    console.log('查询条件:', { where, sortField, sortOrder, limit: parseInt(limit), offset: parseInt(offset) });

    const { count, rows } = await SharedImage.findAndCountAll({
      where,
      include: [
        {
          model: User,
          attributes: ['id', 'username', 'avatar']
        },
        {
          model: AIRole,
          attributes: ['id', 'name', 'avatar'],
          required: false
        }
      ],
      order: [[sortField, sortOrder]],
      limit: parseInt(limit),
      offset: parseInt(offset)
    });

    console.log('查询结果:', { count, rowsLength: rows.length });

    // 如果用户已登录，为每个图片添加点赞状态
    let imagesWithLikeStatus = rows;
    if (req.user) {
      const userId = req.user.id;
      imagesWithLikeStatus = await Promise.all(
        rows.map(async (image) => {
          const isLiked = await UserLike.findOne({
            where: {
              user_id: userId,
              shared_image_id: image.id
            }
          });

          return {
            ...image.toJSON(),
            is_liked: !!isLiked
          };
        })
      );
    } else {
      // 未登录用户，所有图片的点赞状态都是false
      imagesWithLikeStatus = rows.map(image => ({
        ...image.toJSON(),
        is_liked: false
      }));
    }

    res.json({
      success: true,
      data: {
        images: imagesWithLikeStatus,
        pagination: {
          total: count,
          page: parseInt(page),
          limit: parseInt(limit),
          totalPages: Math.ceil(count / limit)
        }
      }
    });
  } catch (error) {
    console.error('获取图片列表失败:', error);
    res.status(500).json({ error: '获取图片列表失败' });
  }
});

// 8. 获取用户点赞过的图片列表
router.get('/liked', authenticateToken, async (req, res) => {
  try {
    const { page = 1, limit = 10 } = req.query;
    const offset = (page - 1) * limit;
    const userId = req.user.id;

    // 首先清理孤立的点赞记录（指向不存在或私有图片的点赞）
    await dbSequelize.query(`
      DELETE ul FROM userlikes ul
      LEFT JOIN sharedimages si ON ul.shared_image_id = si.id
      WHERE ul.user_id = :userId AND (si.id IS NULL OR si.is_public = 0)
    `, {
      replacements: { userId },
      type: dbSequelize.QueryTypes.DELETE
    });

    // 通过UserLike表关联查询用户点赞过的图片
    const { count, rows } = await SharedImage.findAndCountAll({
      include: [
        {
          model: User,
          attributes: ['id', 'username', 'avatar'],
          required: true
        },
        {
          model: AIRole,
          attributes: ['id', 'name', 'avatar'],
          required: false
        },
        {
          model: UserLike,
          where: { user_id: userId },
          attributes: ['created_at'],
          required: true
        }
      ],
      where: {
        is_public: true // 只显示公开的图片
      },
      order: [[UserLike, 'created_at', 'DESC']], // 按点赞时间倒序
      limit: parseInt(limit),
      offset: parseInt(offset)
    });

    // 为每个图片添加点赞状态和点赞数
    const imagesWithLikeInfo = await Promise.all(
      rows.map(async (image) => {
        const likeCount = await UserLike.count({
          where: { shared_image_id: image.id }
        });

        return {
          ...image.toJSON(),
          like_count: likeCount,
          is_liked: true, // 这些都是用户点赞过的图片
          liked_at: image.UserLikes && image.UserLikes[0] ? image.UserLikes[0].created_at : null // 点赞时间
        };
      })
    );

    res.json({
      success: true,
      data: {
        images: imagesWithLikeInfo,
        pagination: {
          total: count,
          page: parseInt(page),
          limit: parseInt(limit),
          totalPages: Math.ceil(count / limit)
        }
      }
    });
  } catch (error) {
    console.error('获取用户点赞图片列表失败:', error);
    res.status(500).json({ error: '获取用户点赞图片列表失败' });
  }
});

// 3. 获取单个图片详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;

    const sharedImage = await SharedImage.findByPk(id, {
      include: [
        {
          model: User,
          attributes: ['id', 'username', 'avatar']
        },
        {
          model: AIRole,
          attributes: ['id', 'name', 'avatar'],
          required: false
        }
      ]
    });

    if (!sharedImage) {
      return res.status(404).json({ error: '图片不存在' });
    }

    // 如果是私有图片，只有作者可以查看
    if (!sharedImage.is_public && (!req.user || req.user.id !== sharedImage.user_id)) {
      return res.status(403).json({ error: '无权访问此图片' });
    }

    // 增加浏览次数
    await sharedImage.increment('view_count');

    // 添加点赞状态信息
    let imageWithLikeStatus = sharedImage.toJSON();
    if (req.user) {
      const isLiked = await UserLike.findOne({
        where: {
          user_id: req.user.id,
          shared_image_id: id
        }
      });
      imageWithLikeStatus.is_liked = !!isLiked;
    } else {
      imageWithLikeStatus.is_liked = false;
    }

    res.json({
      success: true,
      data: imageWithLikeStatus
    });
  } catch (error) {
    console.error('获取图片详情失败:', error);
    res.status(500).json({ error: '获取图片详情失败' });
  }
});

// 4. 更新图片信息
router.put('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const { title, description, category, tags, is_public } = req.body;

    const sharedImage = await SharedImage.findByPk(id);
    if (!sharedImage) {
      return res.status(404).json({ error: '图片不存在' });
    }

    // 只有作者可以修改
    if (sharedImage.user_id !== req.user.id) {
      return res.status(403).json({ error: '无权修改此图片' });
    }

    // 解析标签
    let parsedTags = sharedImage.tags;
    if (tags !== undefined) {
      try {
        parsedTags = typeof tags === 'string' ? JSON.parse(tags) : tags;
      } catch (error) {
        return res.status(400).json({ error: '标签格式错误' });
      }
    }

    await sharedImage.update({
      title: title || sharedImage.title,
      description: description !== undefined ? description : sharedImage.description,
      category: category || sharedImage.category,
      tags: parsedTags,
      is_public: is_public !== undefined ? is_public : sharedImage.is_public
    });

    res.json({
      success: true,
      message: '图片信息更新成功',
      data: sharedImage
    });
  } catch (error) {
    console.error('更新图片信息失败:', error);
    res.status(500).json({ error: '更新图片信息失败' });
  }
});

// 5. 删除图片
router.delete('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;

    const sharedImage = await SharedImage.findByPk(id);
    if (!sharedImage) {
      return res.status(404).json({ error: '图片不存在' });
    }

    // 只有作者或管理员可以删除
    if (sharedImage.user_id !== req.user.id && !req.user.isAdmin) {
      return res.status(403).json({ error: '无权删除此图片' });
    }

    // 删除文件
    const imagePath = path.join(__dirname, '..', 'public', sharedImage.image_path);
    if (fs.existsSync(imagePath)) {
      fs.unlinkSync(imagePath);
    }

    await sharedImage.destroy();

    res.json({
      success: true,
      message: '图片删除成功'
    });
  } catch (error) {
    console.error('删除图片失败:', error);
    res.status(500).json({ error: '删除图片失败' });
  }
});

// 6. 点赞/取消点赞图片
router.post('/:id/like', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    const sharedImage = await SharedImage.findByPk(id);
    if (!sharedImage) {
      return res.status(404).json({ error: '图片不存在' });
    }

    // 检查用户是否已经点赞
    const existingLike = await UserLike.findOne({
      where: {
        user_id: userId,
        shared_image_id: id
      }
    });

    if (existingLike) {
      // 已点赞，执行取消点赞
      await existingLike.destroy();
      await sharedImage.decrement('like_count');

      res.json({
        success: true,
        message: '取消点赞成功',
        data: {
          isLiked: false,
          likeCount: Math.max(0, sharedImage.like_count - 1)
        }
      });
    } else {
      // 未点赞，执行点赞
      await UserLike.create({
        user_id: userId,
        shared_image_id: id
      });
      await sharedImage.increment('like_count');

      res.json({
        success: true,
        message: '点赞成功',
        data: {
          isLiked: true,
          likeCount: sharedImage.like_count + 1
        }
      });
    }
  } catch (error) {
    console.error('点赞操作失败:', error);
    res.status(500).json({ error: '点赞操作失败' });
  }
});

// 7. 获取用户对图片的点赞状态
router.get('/:id/like-status', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    const liked = await UserLike.findOne({
      where: {
        user_id: userId,
        shared_image_id: id
      }
    });

    res.json({
      success: true,
      data: {
        liked: !!liked
      }
    });
  } catch (error) {
    console.error('获取点赞状态失败:', error);
    res.status(500).json({ error: '获取点赞状态失败' });
  }
});

// 7. 获取图片分类列表
router.get('/categories/list', async (req, res) => {
  try {
    const categories = await SharedImage.findAll({
      attributes: ['category'],
      group: ['category'],
      where: { is_public: true }
    });

    const categoryList = categories.map(item => item.category);

    res.json({
      success: true,
      data: categoryList
    });
  } catch (error) {
    console.error('获取分类列表失败:', error);
    res.status(500).json({ error: '获取分类列表失败' });
  }
});

// 8. 获取用户的图片列表
router.get('/user/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const { page = 1, limit = 20 } = req.query;
    const offset = (page - 1) * limit;

    const where = { user_id: userId };

    // 如果不是本人或管理员，只显示公开图片
    if (!req.user || (req.user.id !== parseInt(userId) && !req.user.isAdmin)) {
      where.is_public = true;
    }

    const { count, rows } = await SharedImage.findAndCountAll({
      where,
      include: [
        {
          model: User,
          attributes: ['id', 'username', 'avatar']
        },
        {
          model: AIRole,
          attributes: ['id', 'name', 'avatar'],
          required: false
        }
      ],
      order: [['created_at', 'DESC']],
      limit: parseInt(limit),
      offset: parseInt(offset)
    });

    // 如果用户已登录，为每个图片添加点赞状态
    let imagesWithLikeStatus = rows;
    if (req.user) {
      const currentUserId = req.user.id;
      imagesWithLikeStatus = await Promise.all(
        rows.map(async (image) => {
          const isLiked = await UserLike.findOne({
            where: {
              user_id: currentUserId,
              shared_image_id: image.id
            }
          });

          return {
            ...image.toJSON(),
            is_liked: !!isLiked
          };
        })
      );
    } else {
      // 未登录用户，所有图片的点赞状态都是false
      imagesWithLikeStatus = rows.map(image => ({
        ...image.toJSON(),
        is_liked: false
      }));
    }

    res.json({
      success: true,
      data: {
        images: imagesWithLikeStatus,
        pagination: {
          total: count,
          page: parseInt(page),
          limit: parseInt(limit),
          totalPages: Math.ceil(count / limit)
        }
      }
    });
  } catch (error) {
    console.error('获取用户图片列表失败:', error);
    res.status(500).json({ error: '获取用户图片列表失败' });
  }
});

module.exports = router;